package server.processor;

import server.http.Request;
import server.http.Response;
import server.adapter.Adapter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 *
 * Processor 是Coyote 协议处理接⼝ ，如果说EndPoint是⽤来实现TCP/IP协
 * 议的，那么Processor⽤来实现HTTP协议，Processor接收来⾃EndPoint的
 * Socket，读取字节流解析成Tomcat Request和Response对象，并通过
 * Adapter将其提交到容器处理，Processor是对应⽤层协议的抽象
 *
 * @author  caiwei
 * @date    2020-10-12 11:58
 * @param
 * @return
 */
public class Processor  implements Runnable {
    private final Socket socket;
    private final Adapter adapter;

    public Processor(Socket socket,Adapter adapter){
        this.socket = socket;
        this.adapter = adapter;
        System.out.println(this.getClass().getName()+" recv a request " + socket.getLocalAddress().toString() +" port:"+socket.getPort());
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            adapter.service(request,response);

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
